package com.idanchuang.component.logback;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.ServletContext;

/**
 * @author yjy
 * @date 2019/12/31 15:14
 **/
@Configuration
@ConditionalOnProperty(prefix = "idanchuang.component.logback.sentry", value = "enabled", matchIfMissing = false)
@ConditionalOnClass({HandlerExceptionResolver.class, ServletContext.class})
public class ComponentLogbackSpringSentryAutoConfiguration {

    /**
     * @return Register a HandlerExceptionResolver that sends all exceptions to Sentry
     *     and then defers all handling to the other HandlerExceptionResolvers.
     *     You should only register this if you are not using a logging integration,
     *     otherwise you may double report exceptions.
     */
    @Bean
    @ConditionalOnProperty(prefix = "idanchuang.component.logback.sentry.handler", value = "enabled", havingValue = "true", matchIfMissing = false)
    public HandlerExceptionResolver sentryExceptionResolver() {
        return new io.sentry.spring.SentryExceptionResolver();
    }

    /**
     * @return Register a ServletContextInitializer that installs the SentryServletRequestListener
     *     so that Sentry events contain HTTP request information.
     *     This should only be necessary in Spring Boot applications. "Classic" Spring
     *     should automatically load the `io.sentry.servlet.SentryServletContainerInitializer`.
     */
    @Bean
    public ServletContextInitializer sentryServletContextInitializer() {
        return new io.sentry.spring.SentryServletContextInitializer();
    }

}
